package lee.vioson.remotedata.interceptors

import lee.vioson.remotedata.manager.UserManager
import lee.vioson.remotedata.utils.LogUtil.e
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLEncoder

/**
 * Http 请求公共参数
 */
class CommonRequestInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val token = if (UserManager.INSTANCE.emailLoginResult != null) {
            UserManager.INSTANCE.emailLoginResult?.sjtoken?:""
        } else {
            UserManager.INSTANCE.anonymousLoginResult?.sjtoken?:""
        }
        e("CommonRequestInterceptor:token", token)
        val header = originalRequest.newBuilder()
            .addHeader("sjtoken", token)
            .addHeader("token", token)
        val requestWithHeader = header.build()
        return chain.proceed(requestWithHeader)
    }

    //由于okhttp header 中的 value 不支持 null, \n 和 中文这样的特殊字符,所以这里
    //会首先替换 \n ,然后使用 okhttp 的校验方式,校验不通过的话,就返回 encode 后的字符串
    private fun getValueEncoded(value: String?): String {
        if (value == null) return "null"
        val newValue = value.replace("\n", "")
        var i = 0
        val length = newValue.length
        while (i < length) {
            val c = newValue[i]
            if (c <= '\u001f' || c >= '\u007f') {
                try {
                    return URLEncoder.encode(newValue, "UTF-8")
                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                }
            }
            i++
        }
        return newValue
    }
}